﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Apollo.Core;
using Apollo.Web;
using System.Globalization;
using Apollo;

namespace Apollo.Website
{
    public partial class Controls_Edit_FormItemDateTime : System.Web.UI.UserControl, IFormItem
    {
        public FormItem Item { get; set; }

        public object TargetObject { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.LabelPropertyName.CssClass = "property_name";

            if (!this.IsPostBack)
            {
                this.LabelPropertyName.Text = this.Item.Projection.DisplayName;

                if (this.TargetObject != null)
                { // EXISTING
                    object obj = this.Item.Projection.Apply(this.TargetObject);

                    if (obj != null)
                    {
                        if (!string.IsNullOrEmpty(Apollo.Application.CurrentLanguage.DateTimeFormat))
                            this.TextBoxPropertyValue.Text = ((DateTime)obj).ToString(Apollo.Application.CurrentLanguage.DateTimeFormat, CultureInfo.InvariantCulture);
                        else
                            this.TextBoxPropertyValue.Text = obj.ToString();
                    }
                }
                else {
                    this.TextBoxPropertyValue.Text = this.Item.Projection.EntityProperty.DefaultValue;
                }

                this.TextBoxPropertyValue.Enabled = (this.Item.Type != FormItemType.ReadOnly);
                if (this.Item.Type == FormItemType.ReadOnly)
                    this.TextBoxPropertyValue.CssClass = "property_value property_datetime_disabled";
            }
        }

        public ActionMessage Save(object obj)
        {
            if (this.Item.Type == FormItemType.ReadOnly)
                return null;
            else if (this.Item.Type == FormItemType.Required && this.TextBoxPropertyValue.Text == "")
            {
                LabelPropertyName.CssClass = "property_name_error";
                return new ActionMessage(this.Item.Projection.DisplayName + " can not be null", ActionMessageType.Error);
            }

            try
            {
                if (this.TextBoxPropertyValue.Text == "")
                    this.Item.Projection.SetValue(obj, null);
                else
                {
                    DateTime value = DateTime.ParseExact(this.TextBoxPropertyValue.Text, Apollo.Application.CurrentLanguage.DateTimeFormat, CultureInfo.InvariantCulture);
                    this.Item.Projection.SetValue(obj, value);
                }
            }
            catch (Exception ex)
            {
                return new ActionMessage(this.Item.Projection.DisplayName + " error: " + ex.Message, ActionMessageType.Error);
            }

            return null;
        }
    }
}